﻿#include "SLit.h"
Slit* Slit_setmeory(SListData x)
{
	Slit* temp = NULL;
	temp = malloc(sizeof(Slit));
	if (temp == NULL)
	{
		perror("malloc is donw");
		exit(1);
	}
	temp->sdata = x;
	temp->spr = NULL;
}
	
void Slit_insertbehid(Slit** ps, SListData x)
{
	assert(ps);
	if (*ps == NULL)
	{
		*ps = Slit_setmeory(x);
		(*ps)->sdata = x;
		return;
	}
	Slit* temp = *ps;
	while (temp->spr)
	{
		temp = temp->spr;
	}
	temp->spr = Slit_setmeory(x);
	
}

void Slit_insertfront(Slit** ps, SListData x)
{
	assert(ps);
	if (*ps == NULL)
	{
		*ps = Slit_setmeory(x);
		(*ps)->sdata = x;
		return;
	}
	Slit* temp = Slit_setmeory(x);

	temp->spr = *ps;
	*ps = temp;
}


	
void Slit_print(Slit* ps)
{
	if (ps == NULL)
	{
		printf("NULL\n");
		return;
	}
	while (ps->spr)
	{
		printf("%d->", ps->sdata);
		ps = ps->spr;
	}
	printf("%d->", ps->sdata);
	printf("NULL\n");
}

void Slit_delbehind(Slit** ps)
{
	assert(ps);
	assert(*ps);
	if ((*ps)->spr == NULL)
	{
		free(*ps);
		*ps = NULL;
		return;
	}
	Slit* temp = NULL;
	Slit* temp2 = *ps;
	while (temp2->spr)
	{
		temp = temp2;
		temp2 = temp2->spr;
	}
	free(temp2);
	temp2 = NULL;
	temp->spr = NULL;
}
void Slit_delfront(Slit** ps)
{
	assert(ps && *ps);
	Slit* temp = (*ps)->spr;
	free(*ps);
	*ps = temp;
}

Slit* Slit_Find(Slit* ps, SListData x)
{
	if (ps == NULL)
	{
		return ps;
	}
	do {
		if (ps->sdata == x)
		{
			return ps;
		}
		ps = ps->spr;
	} while (ps);
	return NULL;
}


//在指定位置之前插入数据
void Slit_Insert(Slit** pphead, Slit* pos, SListData x)
{
	assert(pphead);
	assert(*pphead);


	if (*pphead == pos)
	{
		Slit_insertfront(pphead, x);
		return;
	}
	Slit* tmp = *pphead;
	Slit* tmp2 = Slit_setmeory(x);
	while (tmp->spr != pos)
	{
		tmp = tmp->spr;
	}
	tmp->spr = tmp2;
	tmp2->spr = pos;
}

//在指定位置之后插入数据
void Slit_InsertAfter(Slit* pos, SListData x)
{
	Slit* tmp = pos->spr;
	Slit* tmp2 = Slit_setmeory(x);
	pos->spr = tmp2;
	tmp2->spr = tmp;

}

////删除pos节点
void Slit_Erase(Slit** pphead, Slit* pos)
{
	assert(pphead);
	assert(*pphead);
	if (*pphead == pos)
	{
		Slit_delfront(pphead);
		return;
	}
	Slit* tmp = *pphead;
	while (tmp->spr != pos)
	{
		tmp = tmp->spr;
	}
	tmp->spr = pos->spr;
	free(pos);
}

//删除pos之后的节点
void Slit_EraseAfter(Slit* pos)
{
	assert(pos->spr);
	Slit* tmp = pos->spr->spr;
	free(pos->spr);
	pos->spr = tmp;
}
//销毁链表
void SListDesTroy(Slit** pphead)
{
	assert(pphead && *pphead);
	Slit* tmp = *pphead;
	
	
	while (tmp)
	{
		Slit* tmp2 = tmp->spr;
		free(tmp);
		tmp = tmp2;
	} 

	*pphead = tmp;
}
